﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;

namespace SharpOSCAR.Base
{
    /// <summary>
    /// Represents an array of TLVs.
    /// </summary>
    public class TlvBlock : ProtocolData, ITlvContainer
    {
        private LinkedList<Tlv> _TLVs;

        /// <summary>
        /// Default constructor
        /// </summary>
        public TlvBlock()
        {
            _TLVs = new LinkedList<Tlv>();
        }

        /// <summary>
        /// Returns the number of TLVs in the container
        /// </summary>
        public int Count
        {
            get { return _TLVs.Count; }
        }

        /// <summary>
        /// Returns the number of TLVs in the container
        /// </summary>
        public ushort Length
        {
            get { return Convert.ToUInt16(Count); }
        }

        /// <summary>
        /// Adds a TLV to the TlvBlock
        /// </summary>
        /// <param name="value">TLV to add</param>
        public void AddTlv(Tlv value)
        {
            _TLVs.AddLast(value);
        }

        /// <summary>
        /// Removes a TLV from the TlvBlock
        /// </summary>
        /// <param name="value">TLV to remove</param>
        public void RemoveTlv(Tlv value)
        {
            _TLVs.Remove(value);
        }

        /// <summary>
        /// Converts the TlvBlock into a byte array representing the block and all TLVs contained inside of it
        /// </summary>
        /// <returns>Returns a byte array representing the TlvBlock</returns>
        public override byte[] ToByteArray()
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // Write the number of elements to the stream
                U16 lenOfBlock = new U16(Length);
                lenOfBlock.WriteToStream(ms);

                // Write each TLV to the stream
                foreach (Tlv value in _TLVs)
                    value.WriteToStream(ms);
                
                // Return the generated TlvBlock byte array
                return ms.ToArray();
            }
        }
    }
}
